//
//  TableWebSupport.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/10/25.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay

import WebKit

public protocol EeTableWebSupport:TagsRenderDelegate{
    
    var webTemplateName:String{get set}
    var webContainer:EeWebContainner{get set}
    
}

public class EeWebContainner: JoView,WKUIDelegate,WKNavigationDelegate{
    
    public static let updateWebHeightKey = "updateWebHeight"
    public var __webView:WKWebView? = nil
    @objc public var webView:WKWebView{
        get{
            if let v = self.__webView
            {
                return v
            }
            let config = WebConfiguration()
            config.initBlock = { hander,controller in
                controller.add(hander, name: "popToRootController")
                controller.add(hander, name: "shareMessage")
                controller.add(hander, name: "sendToIOS")
                //            controller.add(hander, name: "search")
                //            let appUserInfo =
                //                "function getAppUserInfo(){" +
                //                    "    return {'username':'zhuxietong','age':'16'} ;" +
                //            "}"
                //
                //            let script11 = WKUserScript(source: appUserInfo, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
                //            let script12 = WKUserScript(source: appUserInfo, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
                //
                //            controller.addUserScript(script11)
                //            controller.addUserScript(script12)
            }
            
            
            weak var wself = self
            config.receiveJsAction = {
                message,controller in
                if let one = message.body as? Dictionary<String, AnyObject>
                {
                    let dict = one.mutable_dictionary
                    wself?.receiveJsAction(object: dict)
                }
            }
            let rct = CGRect(x: 0, y: 0, width: Swidth, height: Sheight)
            let webV = WKWebView(frame: rct, configuration: config)
            self.__webView = webV
            return webV
            
        }
    }
    
    open func receiveJsAction(object:NSMutableDictionary)
    {
        
    }
    
    public var heightConstrain:NSLayoutConstraint = NSLayoutConstraint()
    @objc public var changTheHeight:(CGFloat)->Void = {_ in}
    @objc public required init() {
        super.init(frame: [0,0,Swidth,Sheight])
    }
    
    @objc public var tableView:UITableView? = nil
        {
        willSet{
            tableView?.removeObserver(self, forKeyPath: "contentOffset")
        }
        didSet{
            let options: NSKeyValueObservingOptions = [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old]
            tableView?.addObserver(self, forKeyPath: "contentOffset", options: options, context: nil)
        }
    }
    
    
    @objc public var webHeight:CGFloat = 0
    required public init(frame: CGRect) {
        super.init(frame: [0,0,Swidth,Sheight])
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func addLayoutRules() {
        webView.allowsBackForwardNavigationGestures = false
        webView.backgroundColor = ._background
        webView.uiDelegate = self
        webView.navigationDelegate = self
        let options: NSKeyValueObservingOptions = [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old]
        webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: options, context: nil)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.alpha = 0
        let lays = [
            [webView,[ee.T.L.B.R]],
        ]
        self.setEeLays(lays: lays)
    }
    
    public func updateHeight() {
        self.updateWeb(height: webView.scrollView.contentSize.height)
        
    }
    override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "contentSize" {
            if webHeight != webView.scrollView.contentSize.height
            {
                self.webHeight = webView.scrollView.contentSize.height
                webView.scrollView.isScrollEnabled = false
                let frame = webView.frame
                webView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: webHeight)
                let frame1 = self.frame
                self.frame = CGRect(x: frame1.origin.x, y: frame1.origin.y, width: frame1.width, height: webHeight)
                self.updateWeb(height: webView.scrollView.contentSize.height)
            }
        }
        
        if keyPath == "contentOffset" {
            if let tab = self.tableView
            {
                //                if #available(iOS 11.0, *) {
                //                } else {
                if abs(tab.contentOffset.y - offset) > 70
                {
                    webView.setNeedsLayout()
                    offset = tab.contentOffset.y
                }
                //                }
            }
        }
        
    }
    
    public func updateWeb(height:CGFloat){
        webView.layoutIfNeeded()
        self.invalidateIntrinsicContentSize()
        
        self.layoutIfNeeded()
        self.superview?.layoutIfNeeded()
        
        //        if let tab = tableView
        //        {
        //            tab.beginUpdates()
        //            tab.endUpdates()
        //        }
        self.changTheHeight(height)
        webView.alpha = 1
    }
    
    public var offset:CGFloat = 0
    public func updateWebContent(observer scrollView:UIScrollView) {
        if abs(scrollView.contentOffset.y - offset) > 70
        {
            webView.setNeedsLayout()
            offset = scrollView.contentOffset.y
        }
    }
    
    
    public override var intrinsicContentSize: CGSize
    {
        return [Swidth,webHeight]
    }
    deinit {
        webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}



extension EeTableWebSupport where Self: UIViewController
{
    
    public var render:BaseHTMLPage{
        let path = Bundle.main.path(forResource: self.webTemplateName, ofType: "html", inDirectory:"html/template")
        let render = TagsRender(templatePath: path!, model: 0)
        let media_path = Bundle.main.path(forResource: "html", ofType: nil)
        render.mediaBundlePath = media_path
        render.css_names = ["css/app"]
        render.delegate = self
        return render
    }
    
    public func replace(_ tag: String) -> String {
        //        print("lllll000000|\(tag)")
        switch tag {
        case "title":
            return "goods"
        case "content":
            let str = "<img src=\"http://img.aoji.cn/2015/0205/fQTqAmzFH0qm.JPG\">" +
                "<p>码云的名称寓意是 二维码的云服务, 随着移动互联网的发展,智能手机能够做越来越多的事情. 二维码和智能手机的结合无疑给传统的会议管理提供了莫大的帮助. 使用二维码签到,用户可以凭借电子版票务直接签到,不仅省去了组织者印票,邮寄的成本和时间,而且环保干净. 组织者只需要用手机或者码云网提供的扫码枪轻轻一扫,即可完成用户签到. 而且可以实时查看用户报名情况, 会议结束后,可以轻松统计,导出到excel报表.</p>" +
                "<img src=\"http://pic.90sjimg.com/back_pic/qk/back_origin_pic/00/03/43/982b8445024ebf67cc90583232eb94b9.jpg\">" +
                "<img src=\"http://b.hiphotos.baidu.com/image/pic/item/35a85edf8db1cb13d8090cd2d454564e93584b8a.jpg\">" +
            "<img src=\"http://cyjctrip.qiniudn.com/12875/1352218279332p17bb7q3g315d41vma132t1jn41r8i8.jpg\">"
            return str
        default:
            return ""
        }
    }
}

open class WebCell: JoTableCell {
    
    //    var heightConstrain:NSLayoutConstraint = NSLayoutConstraint()
    //
    //    override func addLayoutRules() {
    //        let heightV = UIView()
    //        let lays = [
    //            [heightV,[ee.T.L.B.R],"10"],
    //        ]
    //        heightConstrain = contentView.setEeLays(lays: lays).1.last!
    //        heightConstrain.identifier = "WebCellHeight"
    //
    //    }
    
    
    @objc public weak var webView:EeWebContainner? = nil{
        didSet{
            //            if let v = webView{
            //                contentView.addSubview(v);
            //            }
            //            webView?.webView.load(render: <#T##HTMLPageRender#>)
            if let webV = webView
            {
                if let oldSuperV = webV.superview{
                    if oldSuperV === self.contentView
                    {
                    }
                    else{
                        let cons = oldSuperV.constraints.filter({ (con) -> Bool in
                            if (con.identifier ?? "XX").hasPrefix("WebCellEdeg")
                            {
                                return true
                            }
                            return false
                        })
                        oldSuperV.removeConstraints(cons)
                        webV.removeFromSuperview()
                    }
                }
                else{
                    let lays:TP.lays = [
                        [webV,[ee.T.L.B.R]]
                    ]
                    let cons = contentView.setEeLays(lays: lays).1
                    for (i,con) in cons.enumerated()
                    {
                        con.identifier = "WebCellEdeg\(i)"
                    }
                }
            }
            else{
                let vs = contentView.subviews.filter({ (view) -> Bool in
                    return (view is EeWebContainner)
                })
                if vs.count > 0
                {
                    
                    let webV = vs[0]
                    let cons = contentView.constraints.filter({ (con) -> Bool in
                        if (con.identifier ?? "XX").hasPrefix("WebCellEdeg")
                        {
                            return true
                        }
                        return false
                    })
                    contentView.removeConstraints(cons)
                    webV.removeFromSuperview()
                }
            }
        }
    }
}



open class WebInfoCell: JoTableCell,TagsRenderDelegate,WKUIDelegate,WKNavigationDelegate{
    public var webHeightConstrain = NSLayoutConstraint()
    public let webView = WKWebView(frame: [0,0,Swidth,Sheight])
    public var webHeight:CGFloat = 0
    
    public var finishLoad = false
    open override func addLayoutRules() {
        webView.allowsBackForwardNavigationGestures = false
        webView.backgroundColor = ._background
        webView.uiDelegate = self
        webView.navigationDelegate = self
        let options: NSKeyValueObservingOptions = [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old]
        webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: options, context: nil)
        
        self.eelay = [
            [webView,[ee.T.L.B.R]],
        ]
        //            contentView.backgroundColor = .red
        self.webHeightConstrain = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: Sheight)
        self.webView.addConstraint(webHeightConstrain)
        //        self.webView.load(render: render)
        webView.alpha = 0
        weak var wself = self
        co_delay(delay: 0.1) {
            wself?.showWeb()
        }
    }
    
    public func showWeb() {
        weak var wself = self
        
        UIView.animate(withDuration: 0.02) {
            wself?.webView.alpha = 1
        }
    }
    
    override open func mo_model_reload() {
        //        self.webHeightConstrain.constant = mo.model[float:"__height",0]
        //        contentView.invalidateIntrinsicContentSize()
        //        self.contentView.setNeedsLayout()
        //        self.contentView.layoutIfNeeded()
        
        //        print("ttttt===oooooo|\(mo.model)")
        
        //            self.webView.load(render: render)
    }
    
    open var render:BaseHTMLPage{
        
        let path = Bundle.main.path(forResource: "文章详情", ofType: "html", inDirectory:"html/template")
        let render = TagsRender(templatePath: path!, model: 0)
        let media_path = Bundle.main.path(forResource: "html", ofType: nil)
        render.mediaBundlePath = media_path
        render.delegate = self
        render.css_names = ["css/app"]
        return render
        
    }
    
    open func replace(_ tag: String) -> String {
        //                    print("lllll000000|\(tag)")
        switch tag {
        case "name":
            return "艾维生活|只为品质生活"
        case "time":
            return Date()["yyyy-MM-dd HH:mm"]
        case "logo":
            return __heads.one_str
        case "content":
            let str = "<img src=\"\(__images.one_str)\">" +
                "<p>云隐·西山国家艺术交流中心位于昆明西郊素有“滇中第佳境”之誉的西山森林公园内。致力于助力社会文化公益事业，关注云南当代艺术、培养年轻艺术家。通过跨国文化艺术交流，促进国内艺术家、艺术机构、艺术活动之间的良心忽的，在全国化的瑜伽中谋求当代艺术的不断发展，力求将国内乃至世界范围内一流的策展人及艺术家对于艺术的独特理解以最好的展览形式呈现给广大观众。</p>" +
                "<img src=\"\(__images.one_str)\">" +
                "<p>\(__titles.creat_info(10))</p>" +
                "<img src=\"\(__images.one_str)\">" +
            "<img src=\"\(__images.one_str)\">"
            return str
        default:
            return ""
        }
    }
    
    override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "contentSize" {
            if webView.scrollView.contentSize.height != webHeight
            {
                self.webHeight = webView.scrollView.contentSize.height
                updateCellHeight(height: webView.scrollView.contentSize.height)
            }
        }
    }
    
    
    func updateCellHeight(height:CGFloat) {
        
        self.webHeightConstrain.constant = height
        mo.model["__height"] = "\(height)"
        
        webView.layoutIfNeeded()
        active(ID: "updateTable")
        
    }
    
    
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.scrollView.isScrollEnabled = false
    }
    
    deinit {
        webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
    }
}



